import query from '@dfeidao/atom-nodejs/db/query';



interface Message {
	productid: string;
	formgroup_no: string;
	client_type: string;
}

interface D {
	formid: string;
	action_name: string;
	code: string;
	parent_no: string;
	menu_no: string;
	menu_name: string;
	code_no: string;
	checked: boolean;
	menu: string;
}

export default async function atom(msg: Message, action_id: string, session_id: string, spaceid: string) {
	const systemid = '12';
	const { prepare, exec } = query(action_id, session_id, systemid);

	prepare('pub_menu', ['_id', 'menu_no',
		'menu_name', 'formid', 'parent_no', 'productid'], { productid: msg.productid, client_type: msg.client_type }, 199, 1, [], []);
	const [data] = await exec<D>();
	const rey = new Array();
	data.forEach((item) => {
		rey.push(item.formid);
	});


	const rec = new Array();
	rey.forEach((item) => {
		if (item) {
			rec.push(item);
		}
	});
	// console.log(rec)
	prepare('pub_form_code', ['_id', 'code',
		'action_keyword', 'action_name', 'formid'], { productid: msg.productid, formid: { $in: rec } }, 199, 1, [], []);
	const [rel] = await exec<D>();
	data.forEach((item) => {
		rel.forEach((it) => {
			if (item.formid === it.formid) {
				it.parent_no = item.menu_no,
					it.menu_no = it.code + it.formid,
					it.menu_name = it.action_name,
					it.code_no = it.code;
			}
		});
	});
	const data1 = data.concat(rel);

	const obj = { formgroup_no: msg.formgroup_no, productid: msg.productid };
	if (!msg.formgroup_no) {
		delete obj.formgroup_no;
	}

	prepare('auth_formgroup_form', ['_id',
		'menu_no', 'formid'], obj, 199, 1, [], []);
	const [res] = await exec<D>();
	if (res.length > 0) {
		data1.forEach((item) => {
			item.checked = false;
			res.forEach((it) => {
				if (item.menu_no === it.menu_no) {
					item.checked = true;
				}
			});
		});
	}


	prepare('auth_formgroup_code', ['_id', 'code', 'formid', 'menu_no'], obj, 199, 1, [], []);
	const [ret] = await exec<D>();
	ret.forEach((a) => {
		a.menu = a.code + a.formid;
	});
	if (ret.length > 0) {
		data1.forEach((item) => {
			ret.forEach((it) => {
				if (item.menu_no === it.menu) {
					item.checked = true;
				}
			});
		});
	}

	return data1;
}
